package com.aabte.springdocopenapi.service;

import com.aabte.springdocopenapi.entity.Person;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.TreeMap;

@Service
public class PersonService {

    private static final TreeMap<Long, Person> MOCK_REPOSITORY = new TreeMap<>();

    static {
        MOCK_REPOSITORY.put(1L, Person.builder().id(1L).name("tom").build());
        MOCK_REPOSITORY.put(2L, Person.builder().id(2L).name("jack").build());
        MOCK_REPOSITORY.put(3L, Person.builder().id(3L).name("lucy").build());
    }

    public Person findById(long id) {
        Person person = MOCK_REPOSITORY.get(id);
        if (null == person) {
            throw new PersonNotFoundException("person not exist. id: " + id);
        }
        return person;
    }

    public Collection<Person> findAll() {
        return MOCK_REPOSITORY.values();
    }

    public Person updatePerson(Person newPerson) {
        Long personId = newPerson.getId();
        Person person = MOCK_REPOSITORY.get(personId);
        if (null == person) {
            throw new PersonNotFoundException("person not exist. id: " + personId);
        }
        MOCK_REPOSITORY.put(personId, newPerson);
        return newPerson;
    }

    public Person addPerson(Person newPerson) {
        Long lastId = MOCK_REPOSITORY.lastKey() + 1;
        newPerson.setId(lastId);
        for (; ; ) {
            if (!MOCK_REPOSITORY.containsKey(lastId)) {
                MOCK_REPOSITORY.put(lastId, newPerson);
                return newPerson;
            }
            ++lastId;
        }
    }
}
